from flask import Blueprint, session, redirect, url_for, render_template, request, jsonify
from sqlalchemy import func
from applications.common.utils.response_data import response_success, response_fail
from applications.models.app_update_model import AppUpdateModel
from applications.models.post_model import Post
from applications.models.user_model import User, db
from applications.models.voice_package_model import VoicePackage

bp = Blueprint('user', __name__, url_prefix='/user')


@bp.get("/test")
def text():
    return "text"


@bp.get('/userInfo')
def getUserInfo():
    users = User.query.all()
    user_list = [user.to_dict() for user in users]
    return response_success(data=user_list)


@bp.get('/detail')
def getUserInfoVoiceDetail():
    user_id = request.args.get('id')
    # 获取查询参数 'id' 的值
    if user_id == None:
        return response_fail(msg="缺少参数")

    user_query = db.session.query(
        User,
        func.count(VoicePackage.id).label('voicePackageCount'),
        func.count(Post.uid).label('postCount'),
    ) \
        .outerjoin(VoicePackage, VoicePackage.uid == User.uid) \
        .outerjoin(Post, Post.uid == User.uid) \
        .filter(User.uid == user_id) \
        .group_by(User.uid) \
        .first()

    if user_query is None:
        return response_fail(msg="用户不存在")

    user_data = user_query[0].to_dict()
    user_data['voicePackageCount'] = user_query.voicePackageCount
    user_data['postCount'] = user_query.postCount

    return response_success(data=user_data)


@bp.get("/appUpdate")
def AppUpdate():
    update_entity = db.session().query(AppUpdateModel).filter(AppUpdateModel.has_update == 1).first()
    # updateStatus 0: 无版本更新  1: 有版本更新，不需要强制升级   2: 有版本更新，需要强制升级
    if update_entity:
        return jsonify({
            'code': 0,
            'msg': "",
            'updateStatus': 1,
            'versionCode': update_entity.version_code,
            'versionName': update_entity.version_name,
            'uploadTime': update_entity.create_time,
            'modifyContent': update_entity.update_content,
            'downloadUrl': update_entity.download_url,
            'apkMd5': update_entity.apk_md5, #可无
            'apkSize': update_entity.apk_size,
            'isIgnorable': update_entity.is_ignorable == 1, #1表示可忽略  #可无
        })
